# -*- coding: utf-8 -*-
from PySide2.QtWidgets import *
from PySide2.QtCore import Qt
from PySide2.QtCore import *
from PySide2.QtGui import *
from app.view import ViewFactory

class ProjectDialog(QDialog):

    def __init__(self,parent= None):
        super(ProjectDialog, self).__init__(parent)
        # 模式状态
        self.setWindowModality(Qt.ApplicationModal)
        # 大小
        self.resize(1060,1001)
        # 位置
        self.move(430,0)
        # 标题栏
        self.setWindowTitle("New Project")
        self.setWindowFlags(self.windowFlags()&~Qt.WindowContextHelpButtonHint)
        # self.setWindowFlags(Qt.FramelessWindowHint) # 隐藏边框
        # 显示对话框
        # self.exec()

class BaseDialog(QDialog):

    def __init__(self,parent= None):
        super(BaseDialog, self).__init__(parent)
        # 模式状态
        self.setWindowModality(Qt.ApplicationModal)
        # 大小
        self.resize(1060,800)
        # 位置
        self.move(430,80)
        # 标题栏
        self.setWindowTitle("New Project")
        # self.setWindowFlags(self.windowFlags()&~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(Qt.FramelessWindowHint) # 隐藏边框
        self.setStyleSheet("QDialog { border:1px solid #D1D1D1; }")
        # 显示对话框
        # self.exec()
        self.baseHeight = 36
        self.titleBar = QWidget()
        self.titleBar.setObjectName("shiftshift_titleBar")
        self.titleBar.setMinimumHeight(self.baseHeight)
        self.titleBar.setStyleSheet("QWidget {background:#F2F2F2;border-top:1px solid #D1D1D1;border-left:1px solid #D1D1D1;border-right:1px solid #D1D1D1; }")
        self.searchBar = QWidget()
        self.searchBar.setMinimumHeight(self.baseHeight)
        self.searchBar.setStyleSheet("QWidget {background:#FFFFFF;border:1px solid #D1D1D1; }")

        self.body = QWidget()
        self.body.setStyleSheet("QWidget {background:#FFFFFF;border-left:1px solid #D1D1D1;border-right:1px solid #D1D1D1; }")
        self.statusBar = QWidget()
        self.statusBar.setMinimumHeight(self.baseHeight)
        self.statusBar.setStyleSheet("QWidget {background:#F2F2F2;border:1px solid #D1D1D1; }")

        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0,0,0,0)
        vlayout.setSpacing(0)
        vlayout.addWidget(self.titleBar)
        vlayout.addWidget(self.searchBar)
        vlayout.addWidget(self.body, 1)
        vlayout.addWidget(self.statusBar)
        self.setLayout(vlayout)
        # titleBar
        self.isTitleBarMove = False
        self.titleBarMouseMovePos:QPoint = None

    def mousePressEvent(self, e:QMouseEvent):
        node = self.childAt(e.pos())
        if isinstance(node, QWidget):
            tnode:QWidget = node
            if tnode.objectName() == 'shiftshift_titleBar':
                self.isTitleBarMove = True
                self.titleBarMouseMovePos = e.pos()


    def mouseMoveEvent(self, e:QMouseEvent):
        if self.isTitleBarMove:
            dx = e.x()-self.titleBarMouseMovePos.x()
            dy = e.y()-self.titleBarMouseMovePos.y()
            self.move(self.x()+dx, self.y()+dy)

    def mouseReleaseEvent(self, e:QMouseEvent):
        if self.isTitleBarMove:
            self.isTitleBarMove = False
            self.titleBarMouseMovePos = None

class ShiftShiftDialog(QDialog):

    def __init__(self,parent= None):
        super(ShiftShiftDialog, self).__init__(parent)
        # 模式状态
        self.setWindowModality(Qt.ApplicationModal)
        # 大小
        self.resize(1200,900)
        # 位置
        self.move(430,80)
        # 标题栏
        self.setWindowTitle("New Project")
        # self.setWindowFlags(self.windowFlags()&~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(Qt.FramelessWindowHint) # 隐藏边框
        self.setStyleSheet("QDialog { border:1px solid #D1D1D1; }")
        # 显示对话框
        # self.exec()
        self.baseHeight = 36
        self.titleBar = QWidget()
        self.titleBar.setObjectName("shiftshift_titleBar")
        self.titleBar.setMinimumHeight(self.baseHeight)
        self.titleBar.setStyleSheet("QWidget {background:#F2F2F2;border-top:1px solid #D1D1D1;border-left:1px solid #D1D1D1;border-right:1px solid #D1D1D1; }")
        self.searchBar = QWidget()
        self.searchBar.setMinimumHeight(self.baseHeight)
        self.searchBar.setStyleSheet("QWidget {background:#FFFFFF;border:1px solid #D1D1D1; }")
        self.body = QSplitter(Qt.Horizontal)
        self.body.setStyleSheet("QWidget {background:#FFFFFF;border-left:1px solid #D1D1D1;border-right:1px solid #D1D1D1; }")
        self.statusBar = QWidget()
        self.statusBar.setMinimumHeight(self.baseHeight)
        self.statusBar.setStyleSheet("QWidget {background:#F2F2F2;border:1px solid #D1D1D1; }")

        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0,0,0,0)
        vlayout.setSpacing(0)
        vlayout.addWidget(self.titleBar)
        vlayout.addWidget(self.searchBar)
        vlayout.addWidget(self.body, 1)
        vlayout.addWidget(self.statusBar)
        self.setLayout(vlayout)
        # titleBar
        self.isTitleBarMove = False
        self.titleBarMouseMovePos:QPoint = None
        # 对body进行操作
        self.initBodyLayout()
        # scrollArea = QScrollArea(self.body)
        # scrollAreaWidget = QWidget()
        # scrollAreaVlayout = QVBoxLayout()
        # for i in range(100):
        #     qb = QPushButton()
        #     qb.setText('%1'.format(i))
        #     qb.setMinimumSize(QSize(60, 30))
        #     scrollAreaVlayout.addWidget(qb)
        # scrollAreaWidget.setLayout(scrollAreaVlayout)
        # scrollArea.setWidget(scrollAreaWidget)


    def mousePressEvent(self, e:QMouseEvent):
        node = self.childAt(e.pos())
        if isinstance(node, QWidget):
            tnode:QWidget = node
            if tnode.objectName() == 'shiftshift_titleBar':
                self.isTitleBarMove = True
                self.titleBarMouseMovePos = e.pos()


    def mouseMoveEvent(self, e:QMouseEvent):
        if self.isTitleBarMove:
            dx = e.x()-self.titleBarMouseMovePos.x()
            dy = e.y()-self.titleBarMouseMovePos.y()
            self.move(self.x()+dx, self.y()+dy)

    def mouseReleaseEvent(self, e:QMouseEvent):
        if self.isTitleBarMove:
            self.isTitleBarMove = False
            self.titleBarMouseMovePos = None

    def initBodyLayout(self):
        body_left_widget_style = '''
            QScrollBar:vertical {
                border: 0px;
                background: white;
                width: 15px;
                margin: 0 0 0 0;
            }
            QScrollBar::handle:vertical {
                background: #E3E3E3;
                min-height: 20px;
                border-radius:15px;
            }
        '''
        # self.body.setStyleSheet(splitterStyle)
        self.body.setStyleSheet("QSplitter::handle:horizontal {background: #D1D1D1;}")
        self.body.setHandleWidth(1)
        # body_left_widget = QWidget()
        body_left_widget = QScrollArea()
        body_left_widget.setStyleSheet(body_left_widget_style)
        # body_left_widget.setStyleSheet("background:red;")
        body_right_widget = QWidget()
        # body_right_widget.setStyleSheet("background:green;")
        self.body.addWidget(body_left_widget)
        self.body.addWidget(body_right_widget)
        self.body.setSizes([200,600])

        scrollAreaWidget = QWidget()
        body_left_widget.setWidget(scrollAreaWidget)
        body_left_widget.setWidgetResizable(True)
        body_left_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scrollAreaVlayout = MyVBoxLayout()
        for i in range(100):
            ss1 = Shift_Shift_Body_Left_Cell()
            scrollAreaVlayout.addWidget(ss1)
        # for i in range(100):
        #     qb = QCheckBox(str(i))
        #     scrollAreaVlayout.addWidget(qb)
        scrollAreaWidget.setLayout(scrollAreaVlayout)


        pass


class Shift_Shift_Body_Left_Cell(QWidget):
    def __init__(self,parent= None):
        super(Shift_Shift_Body_Left_Cell, self).__init__(parent)
        self.setContentsMargins(0,0,0,0)
        sizePolicy = self.sizePolicy()
        # print(sizePolicy)
        # sizePolicy.setHorizontalStretch(1)
        sizePolicy.setHorizontalPolicy(QSizePolicy.Expanding)
        sizePolicy.setVerticalPolicy(QSizePolicy.Fixed)
        self.setSizePolicy(sizePolicy)
        # self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        # self.setMinimumSize(QSize(100,200))
        # print(self.layout())
        self.setFixedHeight(100)
        q1 = QWidget(self)
        q1.setStyleSheet("background:red;")
        q1.setMinimumSize(QSize(30,30))
        q1.setMaximumSize(QSize(30,30))
        q1.move(40,0)

class QFlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super(QFlowLayout, self).__init__(parent)

        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)

        self.setSpacing(spacing)

        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None

    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(QFlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())

        margin, _, _, _ = self.getContentsMargins()

        size += QSize(2 * margin, 2 * margin)
        return size

    def doLayout(self, rect, testOnly):
        # 父类容器的x,y,width,height
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            # 布局间隔+组件内布局间隔，组件间的实际间距
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
            # 布局间隔+组件内布局间隔，组件间的实际间距
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)

            nextX = x + item.sizeHint().width() + spaceX
            # 如果组件坐标超过父类容器的宽度，则把组件下移
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()

class MyVBoxLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=0):
        super(MyVBoxLayout, self).__init__(parent)
        self.setContentsMargins(margin, margin, margin, margin)
        self.setSpacing(spacing)
        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None

    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(MyVBoxLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()
        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())
        margin, _, _, _ = self.getContentsMargins()
        size += QSize(2 * margin, 2 * margin)
        print(size)
        return size

    def doLayout(self, rect, testOnly):
        # rect父类组件的x,y位置坐标；与宽高
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            if isinstance(wid, QWidget):
                wid:QWidget = wid
                wid.setMinimumSize(QSize(wid.parent().width(), wid.height()))
                print(wid.height())
                # print(wid.parent().size())
            # 布局间隔+组件内布局间隔，组件间的实际间距
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
            # 布局间隔+组件内布局间隔，组件间的实际间距
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
            y = y + lineHeight + spaceY
            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()